<?php
namespace app\index\controller;
use app\index\model\Finance as FinanceModel;
use think\Db;
class Finance extends Common
{
  /** 
   * 支出添加
   */
  public function add()
  {
    if(request()->isAjax()){
      $data = input('post.');
      $Finance = new FinanceModel();
      if($Finance->allowField(true)->save($data)){
        $this->success('添加成功');
      }else{
        $this->error('添加失败');
      }
      return;
    }
    return $this->fetch();
  }

  /**
   * 支出列表
   */
  public function lst()
  {
    $post = input('get');
    if (preg_match("/^[\x{4e00}-\x{9fa5}]+$/u",$post)) {
      $map['name'] = input('get');
    }
    else
    {
      if (strlen($post) > 0 and strlen($post) < 11 and $post) {
      $map['id'] = input('get');
      }   
    }
    $finance = empty($map) ? Db::name('finance')->order('sort desc')->order('id desc')->paginate(20) : db('finance')->where($map)->order('sort desc')->order('id desc')->paginate($listRows = 20, $simple = false, $config = ['query'=>array('get'=>$post)]);
    $this->assign('finance',$finance);
    return $this->fetch();
  }

  //支出排序
  public function orders()
  {
    if(request()->isPost()) {
      $post = $this->request->post();
      $i = 0;
      foreach ($post['id'] as $k => $val) {
        $order = FinanceModel::where('id',$val)->value('sort');
        if($order != $post['sort'][$k]) {
          if(false == FinanceModel::where('id',$val)->update(['sort'=>$post['sort'][$k]])) {
            return $this->error('更新失败');
          } else {
            $i++;
          }
        }
      }
      return $this->success('更新成功','finance/lst');
    }
  }

  /**
   * 支出修改
   */
  public function edit($id)
  {
    $code = db('finance')->find($id);
    if(request()->isAjax()){
      $data = input('post.');
      $finance = new FinanceModel();
      $res = $finance->allowField(true)->save($data,['id'=>input('id')]);
      if($res !== false){
        $this->success('修改成功');
      }else{
        $this->error('修改失败');
      }
      return;
    }
    if(!$code){
      $this->error("该用户不存在",'lst');
    }
    $this->assign('finance',$code);
    return view();
  }

  //消费
  public function spend($id)
  {
    $code = db('finance')->find($id);
    if(request()->isAjax()){
      $data = input('post.');
      $finance = new FinanceModel();
      $consume = $data['balances'];
      $num = $code['balances']+$data['balances'];
      $data['balances'] = $num;
      $res = $finance->allowField(true)->save($data,['id'=>input('id')]);
      if($res !== false){
        //写入日志
        addLog($uid = $finance->id , $caozuo = '支出' , $balance = $consume);
        $this->success('支出成功');
      }else{
        $this->error('支出失败');
      }
      return;
    }
    if(!$code){
      $this->error("该用户不存在",'lst');
    }
    $this->assign('finance',$code);
    return view();
  }

}